(function ($, document, window) {

	/**
	 * 默认配置
	 */
	var
	clientWidth = window.innerWidth || document.documentElement.clientWidth,
	clientHeight = window.innerHeight || document.documentElement.clientHeight,
	_defaults = {
		content: '',				// 消息内容
		title: '\u6d88\u606f',		// 标题. 默认'消息'
		bottom:true,				// 是否显示底部
		buttons: null,				// 自定义按钮
		initialWidth: 0,//clientWidth/3,		// 初始宽
        initialHeight: 0,//clientHeight/3,		// 初始高
		width: 'auto',				// 内容宽度
		height: 'auto',				// 内容高度
		minWidth: 0,				// 最小宽度限
		minHeight: 0,				// 最小高度限
		maxWidth: 2*(clientWidth)/3,				// 最大宽度限制 0为不限制
		maxHeight: 2*(clientHeight)/3,				// 最大高度限制 0为不限制
		skin: '1',					// 皮肤名
		icon: null,					// 消息图标名称
		timeout: false,				// 自动关闭时间
		rel: false,					// 组
		href: false,
		iframe:false,
		esc: true,					// 是否支持Esc键关闭
		focus: true,				// 是否支持对话框按钮自动聚焦
		show: true,					// 初始化后是否显示对话框
		follow: null,				// 跟随某元素(即让对话框在元素附近弹出)
		overlay: false,				// 是否遮罩
		overlayColor: '#000',		// 遮罩颜色
		overlayOpacity: .6,			// 遮罩透明度
		fixed: true,				// 是否静止定位
		left: 0,					// X轴坐标'50%'
		top: 0,						// Y轴坐标'38.2%'
		zIndex: 1000,				// 对话框叠加高度值(重要：此值不能超过浏览器最大限制)
		resizable: true,			// 是否允许用户调节尺寸
		draggable: true,			// 是否允许用户拖动位置
	
		/*Dialog CallBack*/
		onOpen: false,				// 加载前执行
        onLoad: false,				// 内容加载前执行 
        onComplete: false,			// 内容加载后执行
        onCleanup: false,			// 关闭前执行
        onClosed: false				// 关闭后执行
	},
	_$window = $(window),
	_$document = $(document),
	_elem = document.documentElement,
	_$html = $('html'),
	_$body = $('body'),
	_isIE6 = window.VBArray && !window.XMLHttpRequest,
	_isMobile = 'createTouch' in document && !('onmousemove' in _elem)
		|| /(iPhone|iPad|iPod)/i.test(navigator.userAgent),
	_overlay = false,
	_parseParameters = function (url) {
		var result = {};
		
		var ms = url.match(/\?(.+)/);
		if(!ms || ms.length != 2) return result;

		var kvs = ms[1].split('&');
		for(var i=0;i<kvs.length;i++) {
			var kv = kvs[i].split('=');
			result[kv[0]] = kv[1];
		}
		return result;
	},
	/**
	 * 定位(相对于可视区域)
	 * @param	left {Number}
	 * @param	top  {Number}
	 */
	_setPosition = function(elem,isFixed,left,top){//_setPosition(this.dom.wrap[0],this.options.fixed);
		var style = elem.style;
		if(_isIE6){
			style.removeExpression('left');
			style.removeExpression('top');
			style.position = 'absolute';
			if(isFixed){
				if (_$html.css('backgroundAttachment') !== 'fixed' && _$body.css('backgroundAttachment') !== 'fixed') {
					_$html.css({
						zoom: 1,// 避免偶尔出现body背景图片异常的情况
						backgroundImage: 'url(about:blank)',
						backgroundAttachment: 'fixed'
					});
				};
				var wrapLeft = left || parseInt(style.left),
				wrapTop = top || parseInt(style.top),
				docLeft = _$document.scrollLeft(),
				docTop = _$document.scrollTop();
				style.setExpression('left', 'eval(document.documentElement.scrollLeft + '
					+ (wrapLeft - docLeft) + ') + "px"');
				style.setExpression('top', 'eval(document.documentElement.scrollTop + '
					+ (wrapTop - docTop) + ') + "px"');
			}
		}else{
			style.position = isFixed ? 'fixed' : 'absolute';
		}
	},
	_loadJs = function(src){
		var script = document.createElement('script') ;
		script.type = 'text/javascript';
		script.src = src;
		document.getElementsByTagName('head')[0].appendChild(script);
		
	};
	!window['tmpl'] && _loadJs('../tmpl.js?r');
	
	var Dialog = function(options){
		this.options = this.extend(_defaults,options);
		this.init();
	};
	
	Dialog.prototype = {
		version : '0.01',
		extend : function(defaults,options){//老json数据,新的json数据
			for (var i in defaults) {
				if (options[i] === undefined) options[i] = defaults[i];		
			};
			return options;
		},
		template : '<div class="ui-dialog-top fn-clear">\
			    <span class="ui-dialog-title"></span>\
			    <a class="ui-dialog-close" href="javascript:void(0);"><span>close</span></a>\
			 </div>\
			 <div class="ui-dialog-content">\
				<div class="ui-dialog-waiting"></div>\
			 </div>\
			 <div class="ui-dialog-bottom fn-clear">\
				<i class="ui-dialog-resizable"></i>\
			 </div>',
		init : function(){
			
			var dom,
				options = this.options,
				_this = this,
				wrap_w,wrap_h,
				content_w,content_h,
				top_ih,
				bottom_ih,
				isSetSize = true;
			options.onOpen && options.onOpen();
			options.overlay && this.overlay().show();
			this.dom = dom = this.dom || this.getDom();
			options.title ? dom.title.html(options.title) : dom.top.hide();
			options.resizable && dom.resizable.show();
			!options.bottom && dom.bottom.hide();
			this.addEvent();
			this.zIndex();
			top_ih = dom.top.innerHeight();
			bottom_ih = dom.bottom.innerHeight();
			
			var setSize = function(){
				wrap_w = options.width == 'auto' ? dom.wrap.width() : options.width;
				wrap_h = options.height == 'auto' ? dom.wrap.height() : options.height;
				if(options.maxWidth && wrap_w > options.maxWidth){
					wrap_w = options.maxWidth;
					dom.content.width(wrap_w - 20);
					wrap_h = top_ih + dom.content.outerHeight()+bottom_ih;
				}
				if(options.maxHeight && wrap_h > options.maxHeight){
					wrap_h = options.maxHeight;
				}
//				alert(wrap_h+'-'+top_ih+'-'+bottom_ih+"="+(wrap_h - top_ih - bottom_ih));
				dom.content.css({'width':wrap_w - 20,'height':wrap_h - top_ih - bottom_ih -20});
			}
			
			if(options.initialWidth && options.initialHeight){
				dom.content.css({width: options.initialWidth-20,height: options.initialHeight-top_ih-bottom_ih-20});
			}
			
			dom.waiting.html('<img src="'+options.skin+'/images/ajax-loader.gif">').show();
			if(options.content){
				dom.content.html(options.content);
			}else{
				if(options.href){
					if(options.href.indexOf('#') == 0){
						dom.content.html($(options.href.indexOf('?')>0?options.href.substring(0,options.href.indexOf('?')):options.href).html());
					}else if(options.iframe){
						var iframe_name = 'iframe'+new Date().getTime();
						dom.content.html('<iframe name='+iframe_name+' frameborder="0" hspace="0" width="100%" height="100%" src="'+options.href+'"></iframe>');
//						isSetSize = false;
//						if(window.frames[iframe_name].document.readyState == "complete"){
//							setSize();
//						}
					}else{
						isSetSize = false;
//						$(dom.content).load(options.href+'?random=' + (new Date().getTime()),function(){
//							setSize();
//							_this.setPosition();
//						});
						$.get(options.href+'?random=' + (new Date().getTime()),function(data){
							dom.content.html(data);
							setSize();
							_this.setPosition();
						});
					}
				}else if(options.ref){
					
				}
			}
			
			isSetSize && setSize();
			_this.setPosition(0,0,_this.options.position && _this.options.position.call(_this).init);
			
			if(options.timeout){
				this.closeHandle = setTimeout(function () {
					_this.close();
				}, options.timeout*1000);
			}
			
			options.onComplete && options.onComplete.call(this);
		},
		// 获取元素
		getDom : function () {
			var wrap = document.createElement('div'),
				body = document.body;
			wrap.style.cssText = 'position:absolute;left:0;top:0';
			wrap.className = 'ui-dialog';
			wrap.innerHTML = this.template;
			body.insertBefore(wrap, body.firstChild);
			
			var name,
				dom = {wrap: $(wrap)},
				elems = wrap.getElementsByTagName('*');
				
			for (var i = 0,j=elems.length; i < j; i++) {
				(name = elems[i].className.match(/ui-dialog-([\w]+)/)) ? dom[name[1]] = $(elems[i]) : '';
			};
			return dom;
		},
		setPosition : function (left, top,init) {
			var	wrap = this.dom.wrap[0],
				isFixed = _isIE6 && this.options.fixed,
				docLeft = _$document.scrollLeft(),
				docTop = _$document.scrollTop(),
				sl = isFixed ? docLeft : 0,
				st = isFixed ? docTop : 0,
				ww = _$window.width(),
				wh = _$window.height(),
				ow = wrap.offsetWidth,
				oh = wrap.offsetHeight,
				left = left || this.options.left || 0,
				top = top || this.options.top || 0;

			if(this.options.position){
				var pos = this.options.position.call(this);
				left = pos.left;
				top = pos.top;
			}
			
			if(init){
				init(_setPosition(wrap,this.options.fixed,left,top));
			}else{
				if(!left){
					left = (ww - ow)/2 + sl;
				}
				if(!top){
					top = (wh - oh)/3 + st;
				}
//				wrap.style.left = left + 'px';
//				wrap.style.top = top + 'px';
				this.dom.wrap.animate({left:left+ 'px',top:top+ 'px'});

				_setPosition(wrap,this.options.fixed);
			}
		},
		close : function(){
			this.closeHandle && clearTimeout(this.closeHandle);
			var _this = this,
			close = function(){
				_this.removeEvent();
				_this.options.overlay && _this.overlay().hide();
				_this.dom.wrap.remove();
			};
			this.options.onCleanup ? this.options.onCleanup.call(this,close) : close();
			this.options.onClosed && this.options.onClosed.call(this);
		},
		zIndex : function(){
			this.dom.wrap.css('zIndex',++_defaults.zIndex);
		},
		addEvent : function () {
			var resizeHandle,
				_this = this,
				buttons = this.options.buttons,
				buttonsSize = buttons && buttons.length,
				button,
				buttonCallbacks = {};
				
			if(buttonsSize > 0){
				for(var i = 0 ; i < buttonsSize ; i++){
					button = buttons[i];
					if(button['name']){
						var btn = document.createElement('button');
						btn.innerHTML = button['name'];
						btn.disabled = button.disabled;
						button.className && (btn.className = button.className);
						buttonCallbacks[button['name']] = button.callback;
						$(btn).bind('click',function(){
							var name = this.innerHTML;
							buttonCallbacks[name]? buttonCallbacks[name]()!== false && _this.close() : _this.close();
						});
						_this.dom.bottom[0].appendChild(btn);
					}
				}
			};
			
			// 监听点击
			this.dom.close && this.dom.close.bind('click',function(){
				_this.close();
			});
			this.dom.wrap//.bind('click', function (event) {
//				var target = event.target, callbackID;
//				
//				if (target.disabled) return false; // IE BUG
//				
//				if (target === DOM.close[0]) {
//					that._click(config.cancelVal);
//					return false;
//				} else {
//					callbackID = target[_expando + 'callback'];
//					callbackID && that._click(callbackID);
//				};
//				
//				that._ie6SelectFix();
//			})
			.bind('mousedown', function () {
				_this.zIndex();
			});
			_$window.bind('resize', function(){
				resizeHandle && clearTimeout(resizeHandle);
				resizeHandle = setTimeout(function () {
					_this.setPosition();
				}, 40);
			});
		},
		// 卸载事件代理
		removeEvent: function () {
			this.dom.wrap.unbind();
			_$window.unbind('resize');
		},
		//背景覆盖层
		overlay : function() {
			if(!_overlay){
				_overlay = document.createElement('div');
//				_overlay.className = 'ui-dialog-overlay';
//				_defaults.zIndex--;
				$(_overlay).css({
					position: 'absolute',
					top: '0px',
					left: '0px',
					width: '100%',
					height: _$document.height(),
					background: this.options.overlayColor,
					opacity: 0
				});
				$('body')[0].appendChild(_overlay);
			}
			var _this = this;
			return {
				show:function(){
					$(_overlay).css('zIndex',++_defaults.zIndex).fadeTo(150,_this.options.overlayOpacity,function(){
						$(this).show();
					});
				},
				hide:function(){
					$(_overlay).fadeTo(150,0,function(){
						$(this).hide();
					});
				}
			};
		}
		//,
//		returnFns:{
//			close : function(){this.close();}
//		}
	}; 
	window.dialog = $.fn.dialog = function(options){
		var t = typeof this.open;
		if(t === 'function' || t === 'object'){
			new Dialog(options);
		}else{
			$(this).click(function(){
				var options = options || {};
				options.title	=	options.title || this.title;
				//#id?width=200&height=100&iframe=true
				options.href	=	options.href || this.getAttribute('href') || this.alt;
				options.rel		=	options.rel || this.rel || false;
				var parameters  = _parseParameters(options.href);
				for(var key in parameters){
					options[key] = options[key] || parameters[key];
				}
				new Dialog(options);
				return false;
			});
		}
	}
	
	/**
	 * alert
	 * @param	content {String}	消息内容
	 * @param	icon	{String}	图标
	 * @param	cb		{Function}	回调
	 * @param	title	{String}	标题
	 */
	dialog.alert = function (content,icon,cb,title) {
	    dialog({
	        id: 'Alert',
	        title: title,
	        content: content,
	        initialWidth: 0,
	        width:300,
	        icon: icon || 'warning',
	        fixed: true,
	        overlay: true,
	        resizable:false,
	        buttons:[{name: '确定',className:'highlight',callback:cb}]
	    });
	};
	
	/**
	 * confirm
	 * @param	content	{String}	消息内容
	 * @param	yes		{Function}	确定按钮回调函数
	 * @param	no		{Function}	取消按钮回调函数
	 * @param	title	{String}	标题
	 */
	dialog.confirm = function (content, yes, no,title) {
	    dialog({
	        id: 'Confirm',
	        title: title,
	        content: content,
	        initialWidth: 0,
	        width:300,
	        icon: 'question',
	        fixed: true,
	        overlay: true,
	        resizable:false,
	        buttons:[{name: '确定',className:'highlight',callback:yes},{name: '取消',callback:no}]
	    });
	};
	

	/**
	 * prompt
	 * @param	question{String}	问题
	 * @param	answer	{Function}	默认答案
	 * @param	yes		{Function}	确定按钮回调函数. 接收参数：输入值
	 * @param	no		{Function}	取消按钮回调函数
	 * @param	title	{String}	标题
	 */
	dialog.prompt = function (question,answer, yes, no,title) {
		question = question || '';
		answer = answer || '';
	    var input;
	    dialog({
	        id: 'Prompt',
	        title: title,
	        content: [
	  	            '<div style="margin-bottom:5px;font-size:12px">',
	  	            	question,
	  	            '</div>',
	  	            '<div>',
	  	                '<input value="',
	  	                	answer,
	  	                '" style="width:18em;padding:6px 4px" />',
	  	            '</div>'
	  	            ].join(''),
	  	    initialWidth: 0,
	  	    width:300,
	        icon: 'question',
	        fixed: true,
	        overlay: true,
	        resizable:false,
	        buttons:[{name: '确定',className:'highlight',callback:function(){
	        	yes && yes(input.value);
	        }},{name: '取消',callback:no}],
	        onComplete: function () {
	            input = this.dom.content.find('input')[0];
	            input.select();
	            input.focus();
	        }
	    });
	};
	
	/**
	 * alert
	 * @param	content {String}	消息内容
	 * @param	timeout	{Number}	延迟时间(/秒)
	 * @param	icon	{String}	图标
	 * @param	cb		{Function}	回调
	 * @param	title	{String}	标题
	 */
	dialog.tips = function(content,timeout,icon,cb,title){
		 dialog({
	        id: 'Tips',
	        title: title || '',
	        content: content,
	        timeout: timeout||2,
	        bottom: false,
	        initialWidth: 0,
	        maxWidth: 300,
	        icon: icon || '',
	        fixed: true,
	        overlay: true,
	        onClosed: cb
	    });
	};
	
	/**
	 * notice
	 * @param	title	{String}	标题
	 * @param	content {String}	消息内容
	 * @param	timeout	{Number}	延迟时间(/秒)
	 * @param	icon	{String}	图标
	 * @param	cb		{Function}	回调
	 */
	dialog.notice = function(title,content,timeout,icon,cb){
		 dialog({
	        id: 'Notice',
	        title: title,
	        content: content,
	        initialWidth: 0,
	        width:300,
	        icon: icon || '',
	        fixed: true,
	        timeout: timeout,
	        resizable:false,
		 	position:function(){
		 		var wrap = this.dom.wrap;
		 		return {'init':function(){
		 			wrap.css({'top': _$window.height() + 'px','left':_$window.width()-2 - wrap.width()})
					.animate({'top': _$window.height()-2 - wrap.height() + 'px'});
		 		},'top':_$window.height()-2 - wrap.height(),'left':_$window.width()-2 - wrap.width()};
		 	},
		 	onCleanup:function(close){
		 		this.dom.wrap.animate({'top': _$window.height()+ (_isIE6?_$document.scrollTop():0) + 'px'},close);
		 	}
	    });
	};
}(jQuery, document, this));